package com.qiyun.dinghuohui.utils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;

/**
 * Created by xlm on 2018\5\25 0025
 * 重写CountDownTImer 增加 onStart()
 */
public abstract class CountDownTimer {

    private long mMillisInFuture;
    private long mCountdownInterval;
    private long mStopTimeInFuture;
    private boolean mCancelled = false;

    public CountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
    }

    public synchronized final void cancel() {
        mCancelled = true;
        mHandler.removeMessages(MSG);
    }

    public synchronized final CountDownTimer start() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();
            return this;
        }
        mHandler.sendMessage(mHandler.obtainMessage(START));
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }

    public synchronized final void stop() {
        cancel();
    }

    public abstract void onStart();

    public void reStart() {
        cancel();
        start();
    }

    public abstract void onTick(long millisUntilFinished);

    public abstract void onFinish();

    private static final int MSG = 1;
    private static final int START = 2;

    // handles counting down
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized (CountDownTimer.this) {
                switch (msg.what) {
                    case MSG:
                        if (mCancelled) {
                            return;
                        }
                        final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();
                        if (millisLeft <= 0) {
                            onFinish();
                        } else if (millisLeft < mCountdownInterval) {
                            sendMessageDelayed(obtainMessage(MSG), millisLeft);
                        } else {
                            long lastTickStart = SystemClock.elapsedRealtime();
                            onTick(millisLeft);
                            long delay = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();
                            while (delay < 0) delay += mCountdownInterval;
                            sendMessageDelayed(obtainMessage(MSG), delay);
                        }
                        break;
                    case START:
                        onStart();
                        break;
                }
            }
        }
    };
}
